import os
import json
import csv
from datetime import datetime
import configparser
from tkinter import filedialog

# 设置文件夹路径和IMEI号
folder_path = filedialog.askdirectory() # 使用原始字符串


config = configparser.ConfigParser()
config.read('configure.ini')
imei_number = int(config.get('Section1', 'IMEI'))

def split_combined_jsons(content):
    """分割无分隔符拼接的JSON字符串，返回单个JSON字符串列表，并打印每个JSON的起始位置"""
    json_strings = []
    start = 0  # 记录当前JSON的起始索引（从0开始）
    depth = 0  # 括号嵌套深度（{加1，}减1）
    
    for i, char in enumerate(content):
        if char == '{':
            depth += 1
        elif char == '}':
            depth -= 1
            # 当深度归0时，说明一个完整的JSON结束
            if depth == 0:
                # 截取从start到当前位置的字符串（包含当前}）
                json_str = content[start:i+1].strip()
                if json_str:  # 跳过空字符串
                    # 打印当前JSON的起始位置（start）和结束位置（i）
                    print(f"JSON起始位置: {start}，结束位置: {i}")
                    json_strings.append(json_str)
                start = i + 1  # 更新下一个JSON的起始位置
    
    return json_strings

# 定义一个函数来提取文件中的电量数据
def extract_battery_data(file_path):
    battery_data = []
    with open(file_path, 'r') as file:
        # 加载JSON数据
        content = file.read()

    json_strings = split_combined_jsons(content)
    #print(json_strings)
    if not json_strings:
        print(f"文件 {file_path} 中未找到有效的JSON对象")
        return battery_data
        
        # 逐个解析JSON并提取数据
    for idx, json_str in enumerate(json_strings, 1):
        data = json.loads(json_str)  # 解析单个JSON

        #print(data)
        for log in data.get("Logs", []):
            # 检查每个日志项是否有Parsed字段
            parsed_list = log.get("Parsed", [])
            for parsed in parsed_list:
                # 获取Body中的Records
                body = parsed.get("Body", {})
                records = body.get("Records", [])
                
                # 遍历每个记录提取电池数据
                for record in records:
                    generated_time = record.get("GeneratedTime", "未找到时间")
                    
                    # 查找Percentage值
                    percentage = "未找到百分比"  # 默认值
                    data_ids = record.get("DataIDs", [])
                    #print(data_ids)
                    for data_id in data_ids:
                        if data_id.get("ID") == 10:
                            data_dict = data_id.get("Data", {})
                            if "Percentage" in data_dict:
                                percentage = data_dict["Percentage"]
                            elif "InternalBatteryPercentage" in data_dict:
                                percentage = data_dict["InternalBatteryPercentage"]
                            print(percentage)
                            break
                    
                    # 只添加有有效百分比的记录（排除默认的“未找到百分比”）
                    if percentage != "未找到百分比":
                        battery_data.append((generated_time, percentage))
    
    return battery_data

# 在文件夹中查找包含特定IMEI号的文件
def find_files_with_imei(folder_path, imei_number):
    matching_files = []
    imei_str = str(imei_number)
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if imei_str in file:
                matching_files.append(os.path.join(root, file))
    return matching_files

# 将提取的数据按时间顺序排序并生成表格
def generate_table(battery_data_list):
    # 将所有数据合并到一个列表中
    all_data = [data for sublist in battery_data_list for data in sublist]
    # 按时间顺序排序
    all_data.sort(key=lambda x: datetime.strptime(x[0], '%Y-%m-%d %H:%M:%S'))
    # 写入CSV文件
    with open('battery_data.csv', 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(['Timestamp', 'Battery Level (%)'])
        csvwriter.writerows(all_data)
    print("Battery data table has been generated as 'battery_data.csv'.")

# 主函数
def main():
    # 查找包含IMEI号的文件
    matching_files = find_files_with_imei(folder_path, imei_number)
    #print(matching_files)
    
    if not matching_files:
        print("No files found with the specified IMEI number.")
        return

    # 提取每个文件中的电量数据
    battery_data_list = []
    
    for file_path in matching_files:
        print(file_path)
        battery_data = extract_battery_data(file_path)
        print("battery_data",battery_data)
        if battery_data:
            battery_data_list.append(battery_data)

    # 如果有提取到数据，生成表格
    if battery_data_list:
        generate_table(battery_data_list)
    else:
        print("No battery data found in the files.")

if __name__ == "__main__":
    main()
